package MyApp::Controller::Books;
use Moose;
use namespace::autoclean;

BEGIN { extends 'Catalyst::Controller::HTML::FormFu'; }

=head1 NAME

MyApp::Controller::Books - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index

=cut

sub index :Path :Args(0) {
    my ( $self, $c ) = @_;

    $c->response->body('Matched MyApp::Controller::Books in Books.');
}

sub base :Chained('/') :PathPart('books') :CaptureArgs(0) {
    my ( $self, $c ) = @_;

    $c->stash(resultset => $c->model('DB::Book'));
    $c->log->debug('*** INSIDE BASE METHOD ***');

    $c->load_status_msgs;
}

sub list :Chained('base') :PathParth('list') :Args(0) {
    my ( $self, $c ) = @_;


    $c->stash(books => [$c->model('DB::Book')->search({},{order_by => 'title DESC'})]);
    #$c->stash(template => 'books/list.tt2');
}

sub url_create :Chained('base') :PathPart('url_create') :Args(3) {
    my ( $self, $c, $title, $rating, $author_id ) = @_;

    if ($c->check_user_roles('admin')) {
        my $book = $c->model('DB::Book')->create({
                title => $title,
                rating => $rating
            });
        $book->add_to_book_authors({author_id => $author_id});
        $c->stash(book     => $book,
                  template => 'books/create_done.tt2'
         );
    } else {
        $c->response->body('Unauthorized!');
    }
}

sub form_create :Chained('base') :PathPart('form_create') :Args(0) {
    my ( $self, $c ) = @_;

    $c->stash(template => 'books/form_create.tt2');
}

sub form_create_do :Chained('base') :PathPart('form_create_do') :Args(0) {
    my ( $self, $c ) = @_;

    my $title     = $c->request->params->{title}     || 'N/A';
    my $rating    = $c->request->params->{rating}    || 'N/A';
    my $author_id = $c->request->params->{author_id} || '1';

    my $book = $c->model('DB::Book')->create({
            title   => $title,
            rating  => $rating,
        });

    $book->add_to_book_authors({author_id => $author_id});
    $c->stash(book     => $book,
              template => 'books/create_done.tt2'
             );
}

sub object :Chained('base') :PathPart('id') :CaptureArgs(1) {
    my ( $self, $c, $id ) = @_;

    $c->stash(object => $c->stash->{resultset}->find($id));
    die "Book $id not found" if !$c->stash->{object};
    $c->log->debug("*** INSIDE OBJECT METHOD for obj id=$id ***");
}

sub delete :Chained('object') :PathPart('delete') :Args(0) {
    my ( $self, $c ) = @_;

    $c->detach('/error_noperms')
        unless $c->stash->{object}->delete_allowed_by($c->user->get_object);

    my $id = $c->stash->{object}->id;
    $c->stash->{object}->delete;
    #$c->stash->{status_msg} = "Book deleted";
    $c->response->redirect($c->uri_for($self->action_for('list'),
            {mid => $c->set_status_msg("Deleted book $id")}));
}

sub list_recent :Chained('base') :PathPart('list_recent') :Args(1) {
    my ( $self, $c, $mins ) = @_;
    
    $c->stash(books => [$c->model('DB::Book')->created_after(DateTime->now->subtract(minutes => $mins))]);
    $c->stash(template => 'books/list.tt2');
}

sub list_recent_tcp :Chained('base') :PathPart('list_recent_tcp') :Args(1) {
    my ( $self, $c, $mins ) = @_;

    $c->stash(books => [
            $c->model('DB::Book')
                ->created_after(DateTime->now->subtract(minutes => $mins))
                ->search({title => {'like', '%TCP%'}})
        ]);

    $c->stash(template => 'books/list.tt2');
}

sub formfu_create :Chained('base') :PathPart('formfu_create') :Args(0) :FormConfig{
    my ( $self, $c ) = @_;

    my $form = $c->stash->{form};

    if ($form->submitted_and_valid) {
        my $book = $c->model('DB::Book')->new_result({});
        $form->model->update($book);
        $c->response->redirect($c->uri_for(($self->action_for('list'),
                    {mid => $c->set_status_msg("Book created")})));
        $c->detach;
    } else {
        my @author_objs = $c->model("DB::Author")->all();
        my @authors;
        foreach (sort {$a->last_name cmp $b->last_name} @author_objs) {
            push(@authors, [$_->id, $_->last_name]);
        }

        my $select = $form->get_element({type => 'Select'});
        $select->options(\@authors);
    }

    $c->stash(template => 'books/formfu_create.tt2');
}

=head1 AUTHOR

cai.yuxuan,,,

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

1;
